package com.wujunshen.update;

import com.wujunshen.dictionary.SynonymDictionary;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;

/**
 * @author frank woo(吴峻申) <br>
 * email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2022/8/24 00:06<br>
 */
@Slf4j
public class SynonymLocationMonitor extends BaseMonitor {
    SynonymLocationMonitor(String location) {
        super(location);
    }

    /**
     * 处理响应
     * @param reader BufferedReader类
     * @throws IOException IO异常
     */
    @Override
    void processResponse(BufferedReader reader) throws IOException {
        String line;
        Map<String, Set<String>> treeMap = new TreeMap<>();

        while ((line = reader.readLine()) != null) {
            Set<String> words = Arrays.stream(line.split(" ")).collect(Collectors.toSet());

            words.forEach(word -> {
                if (treeMap.containsKey(word)) {
                    treeMap.get(word).addAll(new HashSet<>(words));
                } else {
                    treeMap.put(word, new HashSet<>(words));
                }
            });
            log.info(line);
        }

        SynonymDictionary.reloadCustomerSynonyms(treeMap);
        log.info("synonymous sync success.");
    }
}
